﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Mammoth.Entities;
using NHibernate;

namespace Mammoth.Repositories
{
    public class Repository<T> : IRepository<T> where T : Entity
    {
        protected IStatelessSession Session { get; private set; }

        public Repository(IDataSessionFactory session)
        {
            Session = session.GetSession();
        }

        public virtual long Save(Entity entity)
        {
            using (ITransaction trx = Session.BeginTransaction())
            {
                if (entity.Id < 1)
                    Session.Insert(entity);
                else
                    Session.Update(entity);
                trx.Commit();
                return entity.Id;
            }
        }

        public virtual void Delete(Entity entity)
        {
            using (ITransaction trx = Session.BeginTransaction())
            {
                Session.Delete(entity);
                trx.Commit();
            }
        }

        public virtual IEnumerable<T> Get(Expression<Func<T, bool>> condition = null, int page = 0, int pageWidth = -1)
        {
            if (condition == null)
                condition = x => x.Id > 0;

            if (pageWidth != -1)
                return Session.QueryOver<T>().Where(condition)
                    .OrderBy(x => x.CreateDate).Desc
                    .Take(pageWidth).Skip(page * pageWidth).List();
            else
                return Session.QueryOver<T>().Where(condition)
                    .OrderBy(x => x.CreateDate).Desc
                    .List();
        }

        public virtual T Get(long id)
        {
            return Session.Get<T>(id);
        }

        public virtual long Count(string search = null)
        {
            return Session.QueryOver<T>().RowCountInt64();
        }

        public void Dispose()
        {
            Session.Dispose();
        }
    }
}
